﻿module Native

open System.Drawing
open System.Runtime.InteropServices
open System.Text

let THUMB_DIM = 350

(*[<DllImport("User32.dll")>]
extern int FindWindow(string ClassName, string WindowName)
[<DllImport("User32.dll")>]
extern int GetWindowText(nativeint hWnd, StringBuilder lpString, int nMaxCount)
[<DllImport("User32.dll")>]
extern int GetWindowTextLength(nativeint hWnd)
let GetText(hWnd:nativeint) =
    // Allocate correct string length first
    let length       = GetWindowTextLength(hWnd)
    let sb = new StringBuilder(length + 1)
    GetWindowText(hWnd, sb, sb.Capacity) |>ignore
    sb.ToString()
*)

[<DllImport("User32.dll")>]
extern int GetWindowRect(nativeint hWnd, Rectangle& rect)

[<DllImport("User32.dll")>]
extern nativeint DeleteObject(nativeint hWnd)



[<DllImport("User32.dll")>]
extern nativeint GetDC(nativeint ptr)
[<DllImport ("User32.dll")>]
extern bool PrintWindow(System.IntPtr hWnd, System.IntPtr dc, uint32 reservedFlag)


let GetImage(pHwnd:nativeint) =
    (*let mutable r = new Rectangle(0,0,0,0)
    GetWindowRect(pHwnd, &r) |>ignore    // r=(x,y,x2,y2)
    r.Width <- r.Width - r.X
    r.Height <- r.Height - r.Y
    *)
    let bmp = new Bitmap(660,650)//r.Width, r.Height)
    let g = Graphics.FromImage(bmp)
    let ptr = g.GetHdc()

    try
        let hDC = GetDC(pHwnd)   // Get DeviceContext Handles
        // Copy Screen from Process-Handle into Bitmap handle
        PrintWindow(pHwnd, ptr, 0u) |>ignore
        // Delete the DeviceContextHandle
        DeleteObject(hDC) |> ignore
    with | _ -> ()

    g.ReleaseHdc(ptr) // Apply new bitmap handle with graphics
    g.Flush()     // apply changes
    g.Dispose()
    
    bmp.GetThumbnailImage(THUMB_DIM, THUMB_DIM, new Image.GetThumbnailImageAbort( fun () -> false), System.IntPtr.Zero)
   